package com.author.document.model;

import java.util.List;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.Position;

import com.author.util.ServiceRegister;

public final class DocumentService implements DocumentListener {
	public final static String DOCUMENT_SERVICE = "DocumentService";
	
	public DocumentService (ServiceRegister serviceRegister, Document document)
		throws Exception {
		if (serviceRegister != null) {
			try {
				this.docServListeners = 
					serviceRegister.getClientsForService(DOCUMENT_SERVICE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if (document == null) {
			String fmtExceptionMsg = "Document model for listener can't be null";
			throw new Exception (fmtExceptionMsg);
		}
		this.docModel = document;
	}
	
	@Override
	public void changedUpdate(DocumentEvent de) {
		if (de == null) 
			return;		
		
		// Get char count of the document (the actual char count needs to be
		// subtracted by 1 to eliminate the end of line marker character
		this.docCharCount = this.docModel.getLength() - 1;
		if (this.docServListeners != null) {
			for (Object o : this.docServListeners) {
				if (o instanceof DocumentServiceListener) {
					((DocumentServiceListener) o).update(this);
				}
			}
		}
	}

	@Override
	public void insertUpdate(DocumentEvent de) {
		if (de == null) 
			return;
		
		// Get char count of the document (the actual char count needs to be
		// subtracted by 1 to eliminate the end of line marker character
		this.docCharCount = this.docModel.getLength() - 1;
		if (this.docServListeners != null) {
			for (Object o : this.docServListeners) {
				if (o instanceof DocumentServiceListener) {
					((DocumentServiceListener) o).update(this);
				}
			}
		}
	}

	@Override
	public void removeUpdate(DocumentEvent de) {
		if (de == null) 
			return;

		// Get char count of the document (the actual char count needs to be
		// subtracted by 1 to eliminate the end of line marker character
		this.docCharCount = this.docModel.getLength() - 1;
		if (this.docServListeners != null) {
			for (Object o : this.docServListeners) {
				if (o instanceof DocumentServiceListener) {
					((DocumentServiceListener) o).update(this);
				}
			}
		}
	}
	
	/**
	 * @return Count >= 0 of the number of characters in the document
	 */
	public long getDocumentCharCount () {
		return this.docCharCount;
	}
	
	private List<Object> docServListeners = null;	
	private Document docModel = null;	//Document model
	private long docCharCount = 0;	//Document char count
}
